package com.test;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;

import okio.Okio;

public class ThreadPoolReader {
    public static void main(String[] args) {
        long t = System.currentTimeMillis();
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        final File[] files = new File("E:\\download\\download").listFiles();
        CountDownLatch lock = new CountDownLatch(files.length);
        Stream<File> fileStream = Arrays.stream(files).filter(file -> {
            final boolean isFile = file.isFile();
            if (!isFile) lock.countDown();
            return isFile;
        });
        fileStream.forEach(file -> {
            executor.execute(new ReadFileTask(file, lock));
        });

        try {
            lock.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println((System.currentTimeMillis() - t));
        executor.shutdownNow();
    }

    private static class ReadFileTask implements Runnable {
        private File file;
        CountDownLatch lock;

        public ReadFileTask(File file, CountDownLatch lock) {
            this.lock = lock;
            this.file = file;
        }

        @Override
        public void run() {
            String content = null;
            try {
                content = Okio.buffer(Okio.source(file)).readByteString().utf8();
/*                BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(file))));
                String content;
                StringBuilder stringBuilder = new StringBuilder();
                while ((content = reader.readLine()) != null) {
                    stringBuilder.append(content);
                }*/
            } catch (IOException e) {
                System.out.println(file.getAbsolutePath());
                e.printStackTrace();

            } finally {
                lock.countDown();
            }
//            System.out.println(content);
        }
    }
}

